package com.opennews.openplatform.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.opennews.openplatform.myspringbootcore.util.LocalDateTimeToUTCSerializer;
import com.opennews.openplatform.myspringbootcore.util.UTCToLocalDateTimeDeserializer;
import jakarta.annotation.PostConstruct;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.TimeZone;

@Configuration
public class AppConfig {
    @Value("${system.timeZone}")
    private String timeZone;

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // Ensure dates are serialized as ISO-8601.
        // The result would be like "2024-11-20T07:11:50Z".
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeToUTCSerializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new UTCToLocalDateTimeDeserializer());
        objectMapper.registerModule(javaTimeModule);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        return objectMapper;
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @PostConstruct
    public void setUpTimeZone() {
        // Sets the default time zone using the injected value.
        TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
    }
}